var connectDevice = new Object();
var cmdResult = new Object();
var connect = false;
var _discoveryStarted = false;

const Init = 'init'
const Sale = 'sale'
const Recharge = 'recharge'
const Replenishment = 'replenishment'


function init(){
  wx.openBluetoothAdapter({
    success: (res) => {
      console.log('openBluetoothAdapter success', res)
      startBluetoothDevicesDiscovery()
    },
    fail: (res) => {
      if (res.errCode === 10001) {
        wx.onBluetoothAdapterStateChange(function (res) {
          console.log('onBluetoothAdapterStateChange', res)
          if (res.available) {
            startBluetoothDevicesDiscovery()
          }
        })
      }
    }
  })
  wx.getBluetoothAdapterState({
    success: (res) => {
      console.log('getBluetoothAdapterState', res)
      if (res.discovering) {
        onBluetoothDeviceFound()
      } else if (res.available) {
        wx.showLoading({
          title: '正在搜索...',
          icon: 'loading',
          duration: 1500
        })
        startBluetoothDevicesDiscovery()
      }
    }
  })
  if(!Object.keys(connectDevice).length === 0){
    wx.showToast({
      title: '暂时未找到合适设备，请稍后再试',
      duration: 1500
    })
  }
 
}
function checkHardware(device){
  var deviceCode = app.globalData.deviceCode;
  if (device.name == deviceCode){
    return true
  }
  return false;
}
function startBluetoothDevicesDiscovery() {
    if (_discoveryStarted) {
      return
    }
    _discoveryStarted = true
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      success: (res) => {
        console.log('startBluetoothDevicesDiscovery success', res)
        onBluetoothDeviceFound()
      },
    })
  }
  function stopBluetoothDevicesDiscovery() {
    wx.stopBluetoothDevicesDiscovery()
  }
  function onBluetoothDeviceFound() {
    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach(device => {
        if (!device.name && !device.localName) {
          return
        }
        if(checkHardware(device)){
          wx.showLoading({
            title: '正在连接'+device.localName,
          })
           stopBluetoothDevicesDiscovery()
           //自动连接蓝牙
          const deviceId = device.deviceId
          const name = device.name
          connectDevice.deviceId = deviceId
          connectDevice.name = name
          connect = true;
          wx.createBLEConnection({
            deviceId,
            success: (res) => {
              getBLEDeviceServices(deviceId)
            }
          })
        }
      })
    })
  }
function getBLEDeviceServices(deviceId) {
  wx.showToast({
    title: '获取设备服务',
    duration: 1500
  })
  wx.getBLEDeviceServices({
    deviceId,
    success: (res) => {
      console.log('res services',res.services);
      connectDevice.services = res.services
      for (let i = 0; i < res.services.length; i++) {
        if (res.services[i].isPrimary) {
          getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
          return
        }
      }
    }
  })
} 
function getBLEDeviceCharacteristics(deviceId, serviceId) {
  wx.showToast({
    title: '获取设备特征值',
    duration: 1500
  })
  wx.getBLEDeviceCharacteristics({
    deviceId,
    serviceId,
    success: (res) => {
      console.log('getBLEDeviceCharacteristics success', res.characteristics)
      for (let i = 0; i < res.characteristics.length; i++) {
        let item = res.characteristics[i]
        item.serviceId = serviceId
        console.log('getBLEDeviceCharacteristics 1', res.characteristics)
      }
      connectDevice.characteristics = res.characteristics
      //   let item = res.characteristics[i]
      //   if (item.properties.read) {
      //     wx.readBLECharacteristicValue({
      //       deviceId,
      //       serviceId,
      //       characteristicId: item.uuid,
      //     })
      //   }
      //   // if (item.properties.write) {
      //   //   this.setData({
      //   //     canWrite: true
      //   //   })
      //   //   this._deviceId = deviceId
      //   //   this._serviceId = serviceId
      //   //   this._characteristicId = item.uuid
      //   //   // this.cmdInit()
      //   // }
      //   if (item.properties.notify || item.properties.indicate) {
      //     wx.notifyBLECharacteristicValueChange({
      //       deviceId,
      //       serviceId,
      //       characteristicId: item.uuid,
      //       state: true,
      //     })
      //   }
      // }
    },
    fail(res) {
      console.error('getBLEDeviceCharacteristics', res)
    }
  })
  // 操作之前先监听，保证第一时间获取数据
  // wx.onBLECharacteristicValueChange((characteristic) => {
  //   const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
  //   const data = {}
  //   if (idx === -1) {
  //     data[`chs[${this.data.chs.length}]`] = {
  //       uuid: characteristic.characteristicId,
  //       value: ab2hex(characteristic.value)
  //     }
  //   } else {
  //     data[`chs[${idx}]`] = {
  //       uuid: characteristic.characteristicId,
  //       value: ab2hex(characteristic.value)
  //     }
  //   }
  //   // data[`chs[${this.data.chs.length}]`] = {
  //   //   uuid: characteristic.characteristicId,
  //   //   value: ab2hex(characteristic.value)
  //   // }
  //   this.setData(data)
  // })
}
function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}
function buf2hex (buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}
function hex2str(hex) {
  var trimedStr = hex.trim();
  var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
  var len = rawStr.length;
  if (len % 2 !== 0) {
    alert("Illegal Format ASCII Code!");
    return "";
  }
  var curCharCode;
  var resultStr = [];
  for (var i = 0; i < len; i = i + 2) {
    curCharCode = parseInt(rawStr.substr(i, 2), 16);
    resultStr.push(String.fromCharCode(curCharCode));
  }
  return resultStr.join("");
}
function stringToHex(str) {
  var val = "";
  for (var i = 0; i < str.length; i++) {
    val += str.charCodeAt(i).toString(16);
  }
  return val;
}
/**
 * 获取发送的buffer值
 */
function getBufferValue (type,data = ''){
	switch(type){
      case Init:
        var buffer = new ArrayBuffer(3)
        var dataView = new DataView(buffer)
        dataView.setUint8(0, 0xA0)
        dataView.setUint8(1, 0x01)
        dataView.setUint8(2, 0x00)
        return buffer
        break
      case Sale :
        // var data = '1234561234561'
        var buffer = new ArrayBuffer(data.length * 2);
        buffer = '0xA10D' + stringToHex(data)
        var typedArray = new Uint8Array(buffer.match(/[\da-f]{2}/gi).map(function (h) {
          return parseInt(h, 16)
        }))
        return typedArray.buffer
        break;
      case Replenishment:
        // var data = '1234561'
        var buffer = new ArrayBuffer(data.length * 2);
        buffer = '0xA207' + stringToHex(data)
        var typedArray = new Uint8Array(buffer.match(/[\da-f]{2}/gi).map(function (h) {
          return parseInt(h, 10)
        }))
        return typedArray.buffer
        break;
      case Recharge:
        var buffer = new ArrayBuffer(data.length * 2);
        buffer = '0xA30D' + stringToHex(data)
        var typedArray = new Uint8Array(buffer.match(/[\da-f]{2}/gi).map(function (h) {
          return parseInt(h, 16)
        }))
        return typedArray.buffer
        break;
      default:
        let buffer = new ArrayBuffer(3)
        let dataView = new DataView(buffer)
        dataView.setUint8(0, 0xA0)
        dataView.setUint8(1, 0x01)
        dataView.setUint8(2, 0x00)
        return buffer
        break;
    }
}
/**
 * 接收命令返回
 */
function readDevice(deviceId, serviceId, characteristicId) {
  return new Promise(function (resolve, reject) {
    wx.onBLECharacteristicValueChange(function (characteristic) {
      console.log('characteristic value comed:', characteristic)
      // console.log('ab2ascii:', ab2Ascii(characteristic.value))
      const hex = buf2hex(characteristic.value)
      // console.log("run-shoes返回的数据：" + hex)
      // console.log("run-shoes：" + hex2str(hex))
      // cmdResult.response = hex

      resolve(hex2str(hex))
    })
    wx.readBLECharacteristicValue({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId,
      // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
      serviceId,
      // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
      characteristicId,
      success(res) {
        console.log('readBLECharacteristicValue:', res)
      }
    })
    // if(characteristic){
    //   resolve(hex)
    // }
    // reject('硬件返回失败')
    
  })
  // wx.onBLECharacteristicValueChange(function (characteristic) {
  //   console.log('characteristic value comed:', characteristic)
  //   // console.log('ab2ascii:', ab2Ascii(characteristic.value))
  //   const hex = buf2hex(characteristic.value)
  //   console.log("run-shoes返回的数据：" + hex)
  //   console.log("run-shoes：" + hex2str(hex))
  //   cmdResult.response = hex
  // })

  // wx.readBLECharacteristicValue({
  //   // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  //   deviceId,
  //   // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
  //   serviceId,
  //   // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
  //   characteristicId,
  //   success(res) {
  //     console.log('readBLECharacteristicValue:', res)
  //   }
  // })
}
function getDeviceId(){
  if (!connect){
    init()
  }
  console.log('连接硬件信息:',connectDevice)
  return connectDevice.deviceId
}
function sendCmd(buffer){
  if (!connect) {
    init()
  }
  const deviceId = connectDevice.deviceId
  for (let i = 0; i < connectDevice.characteristics.length; i++) {
    let item = connectDevice.characteristics[i]
    const serviceId = item.serviceId
    const characteristicId = item.uuid
    if (item.properties.read) {
      wx.readBLECharacteristicValue({
        deviceId,
        serviceId,
        characteristicId: characteristicId,
      })
    }
    if (item.properties.write) {
      wx.writeBLECharacteristicValue({
        deviceId: deviceId,
        serviceId: serviceId,
        characteristicId: characteristicId,
        value: buffer,
        success(res) {
          console.log('写入数据成功', res)
          cmdResult.send = true
          cmdResult.msg = '指令写入成功'
          readDevice(deviceId, serviceId, characteristicId).then(function(res){
            cmdResult.response = res 
          })
        },
        fail(err) {
          cmdResult.send = false
          cmdResult.msg = '指令写入失败'
          console.log('err', err)
        }
      })
    }
    if (item.properties.notify || item.properties.indicate) {
      wx.notifyBLECharacteristicValueChange({
        deviceId,
        serviceId,
        characteristicId: item.uuid,
        state: true,
      })
    }
  }
}
function sendInitCmd(){
  var buffer = getBufferValue(Init)
  sendCmd(buffer)
}
function sendSaleCmd(data){
  var buffer = getBufferValue(Sale,data)
  sendCmd(buffer)
}
function sendRechargeCmd(data){
  var buffer = getBufferValue(Recharge, data)
  sendCmd(buffer)
}
function sendReplenishmentCmd(data){
  var buffer = getBufferValue(Replenishment, data)
  sendCmd(buffer)
}
function getResult(type){
  switch (type) {
    case Init:
      if(!cmdResult.send){
        cmdResult.response = false
        cmdResult.responseMsg = '未发送指令'
      }
      if (cmdResult.response.substr(0,4) == 'b10D'){
        cmdResult.response = true
        cmdResult.responseMsg = '操作成功'
      }else{
        cmdResult.response = false
        cmdResult.responseMsg = '操作失败'
      }
      break
    case Sale:
    case Replenishment:
    case Recharge:
      if (!cmdResult.send) {
        cmdResult.response = false
        cmdResult.responseMsg = '未发送指令'
      }
      if (cmdResult.response == 'b10132') {
        cmdResult.response = false
        cmdResult.responseMsg = '密码错误'
      } else if (cmdResult.response == 'b10131') {
        cmdResult.response = false
        cmdResult.responseMsg = '未知错误'
      } else if (cmdResult.response == 'b10130') {
        cmdResult.response = true
        cmdResult.responseMsg = '操作成功'
      }
      return cmdResult 
      break;
    default:
      if (!cmdResult.send) {
        cmdResult.response = false
        cmdResult.responseMsg = '未发送指令'
      }
      if (cmdResult.response == 'b10132') {
        cmdResult.response = false
        cmdResult.responseMsg = '密码错误'
      } else if (cmdResult.response == 'b10131') {
        cmdResult.response = false
        cmdResult.responseMsg = '未知错误'
      } else if (cmdResult.response == 'b10130') {
        cmdResult.response = true
        cmdResult.responseMsg = '操作成功'
      }
      return cmdResult
      break;
  }
  return cmdResult
}
function close() {
  connectDevice = new Object()
  connect = false
  wx.closeBLEConnection({
    deviceId: connectDevice.deviceId
  })
}

module.exports = {
  init: init,
  getDeviceId: getDeviceId,
  sendInitCmd: sendInitCmd,
  sendSaleCmd: sendSaleCmd,
  sendRechargeCmd: sendRechargeCmd,
  sendReplenishmentCmd: sendReplenishmentCmd,
  getResult: getResult,
  close: close
}